<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%@ page import="cn.hutool.core.util.RandomUtil" %>
<%@ page import="cn.hutool.http.ContentType" %>
<%@ page import="cn.hutool.http.HttpRequest" %>
<%@ page import="cn.hutool.http.HttpResponse" %>
<%@ page import="cn.hutool.http.HttpUtil" %>
<%@ page import="cn.hutool.json.JSONUtil" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.alibaba.fastjson.serializer.SerializerFeature" %>
<%@ page import="com.google.common.base.Joiner" %>
<%@ page import="org.apache.commons.codec.digest.DigestUtils" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.math.BigDecimal" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.TreeMap" %>
<%
    JSONObject jsonData = new JSONObject();
    String name = Util.null2String(request.getParameter("name"));
    String accBal = "0.00";
    if (!"".equals(name)) {
        String custId = Util.null2String(queryCustomer(name));
         accBal = Util.null2String(queryBalancer(custId));
    }
    jsonData.put("accBal", fDivide(accBal,"100"));
    out.print(jsonData.toJSONString());
%>
<%!
    private static String queryBalancer(String custId) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>queryBalancer>>>>custId=" + custId);
        String url = "https://api.xnzn.net/tengyun-api/leopen/account/balance/query";
        HashMap<Object, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("custId", custId);
        String resultStr = Util.null2String(invokeHandle(url, bodyMap));
        baseBean.writeLog(">>>>>queryBalancer>>>>resultStr=" + resultStr);
        String accBal = "0.00";
        if (!"".equals(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            String code = Util.null2String(resultJson.getString("code"));
            if ("10000".equals(code)) {
                String dataStr = Util.null2String(resultJson.getString("data"));
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                accBal = Util.null2String(dataJson.getString("accBal"));
            }
        }
        return accBal;
    }

    private static String queryCustomer(String custNum) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>queryCustomer>>>>custNum=" + custNum);
        String url = "https://api.xnzn.net/tengyun-api/leopen/customer/query";
        HashMap<Object, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("custNum", custNum);
        String resultStr = Util.null2String(invokeHandle(url, bodyMap));
        baseBean.writeLog(">>>>>queryCustomer>>>>resultStr=" + resultStr);
        String custId = "";
        if (!"".equals(resultStr)) {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            String code = Util.null2String(resultJson.getString("code"));
            if ("10000".equals(code)) {
                String dataStr = Util.null2String(resultJson.getString("data"));
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                JSONArray dataList = JSONArray.parseArray(dataJson.getString("customerList"));
                if (dataList.size() > 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        custId = dataList.getJSONObject(i).getString("custId");
                    }
                }
            }
        }

        return custId;
    }

    private static String invokeHandle(String url, HashMap<Object, Object> bodyMap) {
        /**
         * appid          应用ID（平台提供）
         * appsecret      应用秘钥（平台提供）
         * version        版本号，默认1.0.0
         * signtype       加密方法，md5 / sha256
         * timestamp      当前时间戳
         * nonce          随机数，不小于10位
         * content        请求内容
         * sign           加签字符串
         */

        //应用秘钥
        String appsecret = "ecda26d1add24442b1d5a7af44b7c850";
        //请求内容字典排序，转换为String
        String content = JSON.toJSONString(bodyMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
        //构造请求验签参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appid", "190633894444294144");
        map.put("version", "1.0.0");
        map.put("signtype", "md5");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("nonce", RandomUtil.randomNumbers(10));
        map.put("content", content);
        //生成sign，防篡改
        String toSignStr = Joiner.on("&")
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(map) + "&appsecret=" + appsecret;
        // md5/sha256 加签（其他方式待提供）
        String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();
        map.put("sign", sign);
        //post请求
        map.replace("content", bodyMap);
        //查询组织信息
        HttpRequest request = HttpUtil.createPost(url);
        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
        HttpResponse response = request.execute();
        return response.body();
    }
    // 除法保留2位小数 四舍五入
    public static String fDivide(String a, String b) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.divide(bg2, 2, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }
    //零判断
    public static String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }
%>